"use client";

import { CalendarDays, ExternalLink, Calendar, Share2 } from "lucide-react";
import RecentExams from "@/components/recent-exams";
import { useState, useEffect, Suspense } from "react";
import QRModal from "@/components/qr-modal";
import { useHomePageVisit } from "@/hooks/usePageVisit";
import VisitCount from "@/components/visit-count";
import { useLanguage } from "@/context/language-provider";
import { useRouter, useSearchParams } from "next/navigation";

// 创建一个包含 useSearchParams 的子组件
function SearchParamsHandler() {
  const { setLanguage } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  
  useEffect(() => {
    const intParam = searchParams.get("int");
    if (intParam === "true") {
      // 设置语言为英文
      setLanguage("en");
    } else {
      setLanguage("zh");
    }
  }, [router, searchParams, setLanguage]);
  
  return null;
}

export default function Home() {
  const [dateRange, setDateRange] = useState<"3days" | "7days" | "month">("3days");
  const [qrModalOpen, setQrModalOpen] = useState(false);
  const [shareUrl, setShareUrl] = useState("");
  const { language, setLanguage } = useLanguage();
  const router = useRouter();
  
  // 使用 hook 记录首页访问
  useHomePageVisit();
  
  // 处理打开二维码模态窗口
  const handleOpenQrModal = (customUrl?: string) => {
    setShareUrl(customUrl || window.location.origin);
    setQrModalOpen(true);
  };
  
  return (
    <div className="space-y-12">
      {/* 使用 Suspense 包裹使用 useSearchParams 的组件 */}
      <Suspense fallback={null}>
        <SearchParamsHandler />
      </Suspense>

      <section className="space-y-4">
        <h1 className="text-3xl md:text-4xl lg:text-5xl font-extrabold tracking-tight text-gradient">
          {language === "zh" ? "「造反有理！」" : "Rebellion is Justified!"}
        </h1>
        <p className="text-lg md:text-xl max-w-2xl" style={{ color: 'hsl(var(--foreground) / 0.7)', padding: '0.5rem 0 0.5rem 1.5rem' }}>
          {language === "zh" ? (
            <>
              这里是由汗水与智慧浇灌的花园🌱
              <br />我们鼓励：
              <br />✓ 思维过程还原 ✓ 举一反三技巧
              <br />✓ 错题复盘心得 ✓ 正能量互助
              <br />谢绝❌：原题搬运/答案争议/焦虑宣泄
            </>
          ) : (
            <>
              This is a garden nurtured by sweat and wisdom 🌱
              <br />We encourage:
              <br />✓ Thought process restoration ✓ Analogy techniques
              <br />✓ Error analysis ✓ Positive assistance
              <br />Prohibited ❌: Direct copying/Answer disputes/Anxiety venting
            </>
          )}
        </p>
        <div className="flex flex-wrap gap-3 sm:gap-4 pt-4">
          <a 
            href="/viewer"
            className="modern-button w-full sm:w-auto"
          >
            {language === "zh" ? "浏览回忆" : "Browse Memories"}
            <ExternalLink className="h-4 w-4" />
          </a>
          <a 
            href="/submit" 
            className="flex items-center justify-center gap-2 rounded-xl py-3 px-6 font-medium transition-all border w-full sm:w-auto"
            style={{ 
              backgroundColor: 'hsl(var(--secondary))',
              color: 'hsl(var(--secondary-foreground))',
              borderColor: 'hsl(var(--secondary))'
            }}
          >
            {language === "zh" ? "提交回忆" : "Submit Memory"}
          </a>
          <button
            onClick={() => handleOpenQrModal()}
            className="flex items-center justify-center gap-2 rounded-xl py-3 px-6 font-medium transition-all border-2 hover:scale-105 torch-button w-full sm:w-auto"
            style={{ 
              backgroundColor: 'hsla(38, 92%, 50%, 0.2)',
              color: 'hsl(38, 92%, 50%)',
              borderColor: 'hsla(38, 92%, 50%, 0.3)',
              boxShadow: '0 4px 10px 0 hsla(38, 92%, 50%, 0.25)'
            }}
          >
            {language === "zh" ? "传递火炬" : "Pass the Torch"}
            <Share2 className="h-4 w-4" />
          </button>
          <VisitCount type="homepage" className="flex items-center justify-center w-full sm:justify-start sm:w-auto text-muted-foreground mt-2 sm:ml-2 sm:mt-0" />
        </div>
      </section>

      <section className="glass-panel p-4 md:p-6 lg:p-8 space-y-6 md:space-y-8">
        <div className="flex flex-col sm:flex-row flex-wrap items-start sm:items-center justify-between gap-4">
          <div className="flex items-center">
            <h2 className="text-xl md:text-2xl font-bold flex items-center gap-2 mr-4">
              <CalendarDays className="h-5 w-5 md:h-6 md:w-6 text-primary" />
              {language === "zh" ? "近日考试安排" : "Recent Exam Schedule"}
            </h2>
          </div>
            
          <div className="flex flex-wrap gap-2 w-full sm:w-auto">
            <button
              onClick={() => setDateRange("3days")}
              className={`glass-panel border flex items-center justify-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-all flex-1 sm:flex-none ${
                dateRange === "3days" 
                  ? "border-primary bg-primary/10" 
                  : "hover:bg-secondary/50"
              }`}
              style={{
                color: dateRange === "3days" ? 'hsl(var(--primary))' : 'hsl(var(--foreground) / 0.8)',
                minWidth: '80px'
              }}
            >
              <Calendar className="h-3.5 w-3.5" />
              <span className="whitespace-nowrap">{language === "zh" ? "3天" : "3 Days"}</span>
              {dateRange === "3days" && <span className="ml-1">✓</span>}
            </button>
            <button
              onClick={() => setDateRange("7days")}
              className={`glass-panel border flex items-center justify-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-all flex-1 sm:flex-none ${
                dateRange === "7days" 
                  ? "border-primary bg-primary/10" 
                  : "hover:bg-secondary/50"
              }`}
              style={{
                color: dateRange === "7days" ? 'hsl(var(--primary))' : 'hsl(var(--foreground) / 0.8)',
                minWidth: '80px'
              }}
            >
              <Calendar className="h-3.5 w-3.5" />
              <span className="whitespace-nowrap">{language === "zh" ? "7天" : "7 Days"}</span>
              {dateRange === "7days" && <span className="ml-1">✓</span>}
            </button>
            <button
              onClick={() => setDateRange("month")}
              className={`glass-panel border flex items-center justify-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-all flex-1 sm:flex-none ${
                dateRange === "month" 
                  ? "border-primary bg-primary/10" 
                  : "hover:bg-secondary/50"
              }`}
              style={{
                color: dateRange === "month" ? 'hsl(var(--primary))' : 'hsl(var(--foreground) / 0.8)',
                minWidth: '80px'
              }}
            >
              <Calendar className="h-3.5 w-3.5" />
              <span className="whitespace-nowrap">{language === "zh" ? "本月" : "Month"}</span>
              {dateRange === "month" && <span className="ml-1">✓</span>}
            </button>
          </div>
        </div>
        
        <RecentExams 
          initialDateRange={dateRange} 
          onDateRangeChange={setDateRange}
          onShare={handleOpenQrModal}
        />
      </section>

      {/* QR码模态窗口 */}
      <QRModal 
        isOpen={qrModalOpen} 
        onClose={() => setQrModalOpen(false)} 
        url={shareUrl}
      />
    </div>
  );
}
